﻿[T4Scaffolding.ControllerScaffolder("Caramel database", Description = "Creates entity classes based on database")][CmdletBinding()]
param(     
	[string]$DataSource = ".",
	[parameter(Mandatory = $true)][string]$InitialCatalog,
	[string]$BaseClassType = "Entity",
	[string]$Project,
	[string]$CodeLanguage,
	[string[]]$TemplateFolders,
	[switch]$Force = $false
)

Write-Host "Scaffolding database $InitialCatalog..."

$database = Get-CatalogMetadata -DataSource $DataSource -InitialCatalog $InitialCatalog

# Prepare all the parameter values to pass to the template, then invoke the template with those values

foreach ($schema in $database.Schemas)
{
	foreach ($table in $schema.Tables)
	{
		if ($table.PrimaryKeys.Count -eq 0)
		{
			Write-Host ("Skipping " + $table + " with no primary keys")
			continue
		}

		$defaultNamespace = (Get-Project $Project).Properties.Item("DefaultNamespace").Value
		$outputPath = $table.SingularizedName
		$templateName = "Entity"

		Add-ProjectItemViaTemplate $outputPath -Template $templateName -Model @{
			EntityTypeNamespace = $defaultNamespace;
			BaseClassType = $BaseClassType;
			Table = $table;
		} -SuccessMessage "Added entity {0}" -TemplateFolders $TemplateFolders -Project $Project -CodeLanguage $CodeLanguage -Force:$Force
		
		$outputPath = Join-Path "Mapping" ($outputPath + "Map")
		$templateName = "ClassMap"

		Add-ProjectItemViaTemplate $outputPath -Template $templateName -Model @{
			EntityTypeNamespace = $defaultNamespace;
			Table = $table;
		} -SuccessMessage "Added entity mapping {0}" -TemplateFolders $TemplateFolders -Project $Project -CodeLanguage $CodeLanguage -Force:$Force
	}
}